package com.example.javabasic.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory.Builder;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.nio.file.Path;

/**
 * @description
 * @Author Lin FuYuan
 * @date 2021/5/18
 */
public class CurTst {

    public static void main(String[] args) throws Exception {
        //重试机制
        RetryPolicy rp = new ExponentialBackoffRetry(10000, 30);
        Builder builder = CuratorFrameworkFactory.builder().connectString("172.28.105.21:2181")
                .connectionTimeoutMs(50000)
                .sessionTimeoutMs(50000)
                .retryPolicy(rp);
        CuratorFramework zkClient = builder.build();
        // 放在这前面执行
        zkClient.start();
        watch(zkClient);
        Thread.sleep(Integer.MAX_VALUE);
    }


    public static void watch(CuratorFramework zkClient) throws Exception {
        PathChildrenCacheListener pathChildrenCacheListener = new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                System.out.println(pathChildrenCacheEvent.getType());
                ChildData data = pathChildrenCacheEvent.getData();
                System.out.println(pathChildrenCacheEvent.getData().getPath());
                System.out.println(new String(data.getData()));
            }
        };

        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, "/test/test", true);
        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        pathChildrenCache.start();

    }


}
